<template>
  <div ref="wrapRef" :style="{ height: '400px', width: '100%' }"></div>
</template>
<script lang="ts">
import { defineComponent, ref, nextTick, unref, onMounted } from 'vue';

import { useScript } from '/@/hooks/web/useScript';
import locationIcon from '../../../assets/images/location.png';

const BAI_DU_MAP_URL =
  'https://api.map.baidu.com/api?v=2.0&ak=YEEGBRWn1vyILOQr2yFqmCyRBGYR8651&s=1&callback=onBMapCallback';

export default defineComponent({
  name: 'BaiduMap',
  setup(props, { emit }) {
    const wrapRef = ref<HTMLDivElement | null>(null);
    const { toPromise } = useScript({ src: BAI_DU_MAP_URL });

    const marker = ref();
    const map = ref();

    async function initMap() {
      await toPromise();
      await nextTick();
    }

    window.onBMapCallback = () => {
      const wrapEl = unref(wrapRef);
      const BMap = (window as any).BMap;
      map.value = new BMap.Map(wrapEl);
      const point = new BMap.Point(116.404, 39.915);
      map.value.centerAndZoom(point, 16);
      map.value.enableScrollWheelZoom(true);

      map.value.addEventListener('click', function (e) {
        var pt = new BMap.Point(e.point.lng, e.point.lat);

        const gc = new BMap.Geocoder();
        gc.getLocation(pt, (rs) => {
          console.log(rs.address);
          emit('on-point', {
            lng: e.point.lng,
            lat: e.point.lat,
            address: rs.address,
          });
        });

        var myIcon = new BMap.Icon(locationIcon, new BMap.Size(28, 28));
        if (marker.value) {
          map.value.removeOverlay(marker.value);
        }
        marker.value = new BMap.Marker(pt, { icon: myIcon }); // 创建标注
        map.value.addOverlay(marker.value);
      });
    };

    function search(keyword) {
      const BMap = (window as any).BMap;
      var myGeo = new BMap.Geocoder();
      // 将地址解析结果显示在地图上，并调整地图视野
      myGeo.getPoint(
        keyword,
        function (point) {
          if (point) {
            map.value.centerAndZoom(point, 16);
            map.value.addOverlay(new BMap.Marker(point, { title: keyword }));
            emit('on-point', point);
          }
        },
        '北京市',
      );
    }

    function centerPoint(lon, lat) {
      const BMap = (window as any).BMap;
      const point = new BMap.Point(lon, lat);
      map.value.centerAndZoom(point, 16);
    }

    onMounted(() => {
      initMap();
    });

    return { wrapRef, search, centerPoint };
  },
});
</script>
